import CSDialog from "./CSDialog";
import {Consts} from "./Const";
//WEB-INF/include/_header.jsp定义的上下文路径
declare var ctx :string;

//页面的请求统一使用这个进行发送
export default class AjaxEx {
    private constructor() {
    }
    private static JSON_MIME = 'application/json; charset=UTF-8'

    public static post(url: string, data: any, sucess?: (d? :any)=>void, options?: JQueryAjaxSettings) {
        AjaxEx._ajax('post', url, data, sucess, options);
    }
    public static postJson(url: string, data: any, sucess?: (d? :any)=>void) {
        AjaxEx._ajax('post', url, data, sucess, {contentType: AjaxEx.JSON_MIME});
    }

    public static get(url: string, sucess?: (d? :any)=>void, options?: JQueryAjaxSettings) {
        AjaxEx._ajax('get', url, "", sucess, options);
    }

    public static getJson(url: string, sucess?: (d? :any)=>void) {
        AjaxEx._ajax('get', url, "", sucess, {contentType: AjaxEx.JSON_MIME, async:false});
    }
    public static getJsonData(url: string):any {
        let dt :any;
        AjaxEx._ajax('get', url, "", (d)=> {dt=d}, {contentType: AjaxEx.JSON_MIME , async:false});
        return dt;
    }

    //将object对象转换换成uri串  $.param 方法转换object中的数组有问题
    public static csbitParam(object:any, prefix = "", deep = 0): string {
        let p = "";
        for (let i in object) {
            if ($.isArray(object[i])) {
                $.each(object[i], function (index, value) {
                    p = AjaxEx.csbitParamToPath(prefix, value, deep, p, i);
                });
            } else {
                p = AjaxEx.csbitParamToPath(prefix, object[i], deep, p, i);
            }
        }
        return p;
    }

    //基于jquery form的文件上载提交，ajaxSubmit
    //表单文件 form action 需设置好
    public static upload(idForm: string, sucess?: (d? :any)=>void) {
        $("body").showLoading();

        $(idForm).ajaxSubmit({
            success: function (data) {
                $("body").hideLoading();
                if (data == Consts.SUCCESS) {
                    $(idForm).modal("hide");

                    if (sucess) sucess(data)
                } else CSDialog.error("导入文件出错：" + data.messager)
            },
            error: (data) => {
                CSDialog.error(data)
                $("body").hideLoading();
            }
        });
    }

    //AJAX请求的回应信息各种条件判断 DataTable内置了POST请求，因此对其结果的hook需要使用这个
    public static serverInfo(xhr : any, showTip: boolean = false, sucess?: (d? : any)=>void) {
        switch (xhr.status) {
            case 200:
                let value: any = xhr.responseText;
                //TODO 此处的Json数据可以直接返回调用者,不需要调用者再次JSON.parse
                if (typeof value == "string") {
                    if (value.indexOf("太长时间没有操作，请重新登录！") > -1) {
                        CSDialog.confirm("太长时间没有操作或操作没有权限，现在进入登录页面吗", () => {
                            window.location.href ="/"//重定向到登录页面
                        });
                    } else if (value.substr(0, 1) == '{' || value.substr(0, 1) == '[') {
                        let json: any = value;
                        try {
                            json = JSON.parse(value);
                            if (json.error) {
                                CSDialog.error(json.messager);
                            } else {
                                if (showTip) CSDialog.info("操作成功");
                                if (sucess) sucess(json);
                            }
                        } catch (e) {
                        }
                    } else if (value == Consts.SUCCESS) {
                        if (showTip) CSDialog.info("操作成功");
                        if (sucess) sucess(value);
                    } else {
                        CSDialog.warning(value)
                    }
                }
                else//can not trigger
                {
                    CSDialog.error(value)
                }
                break;
            //HTT请求受限
            case 400:
            case 401:
            case 403:
            case 404:
            case 405:
                CSDialog.warning(xhr.responseText);
                break;
            //其他所有的情况作为错误
            default:
                CSDialog.error("操作过程出错，此次操作无效！" + xhr.responseText);
                break;
        }
    }

    private static csbitParamToPath(pre :any , value:any , deep:any , p:any , i:any ) {
        let temp ="";
        if (typeof value == "object") {
            if (pre == "") {
                temp = i;
            } else {
                if (deep == 1) {
                    temp = pre + '["' + i + '"]';
                } else {
                    temp = pre + '.' + i;
                }
            }
            deep++;
            p += AjaxEx.csbitParam(value, temp, deep);
            deep--;
        } else {
            if (pre == "") {
                temp = i;
            } else {
                if (deep == 1) {
                    temp = pre + '["' + i + '"]';
                } else {
                    temp = pre + '.' + i;
                }
            }
            p += "&" + temp + "=" + encodeURIComponent(value);
        }

        if (deep == 0) {
            pre = "";
        }
        return p;
    }

    private static ajax: JQueryAjaxSettings = {
        async: true,
        data: {},
        dataType: 'json',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        cache: false,
        beforeSend: function () {
            //CSDialog.info("正在处理，请稍候......")
            $("body").showLoading() //mask page
        }
    };

    private static _ajax(method: 'get'|'post', url: string, data: any, sucess?: (d?: any)=>void, opt?: JQueryAjaxSettings) {
        let options = $.extend({},AjaxEx.ajax, opt, {
            method : method,
            url: ctx + url,
            data : data,
            complete : function (xhr :any, textStatus:any) {
                toastr.clear(); //提示窗口使用的是toastr
                $("body").hideLoading();
                AjaxEx.serverInfo(xhr, true, sucess)
            }
        })

        $.ajax(options);
    }
}
